package tcss543.singlehelper;

import java.util.Vector;

import tcss543.DeviceGraph;
import tcss543.Matcher;

public class SingleHelper implements Matcher {

	public boolean Done (Vector<SRequestor> requestors)
	{
		int i;
		
		for( i = 0; i < requestors.size(); i++)
		{
	        if(requestors.elementAt(i).done == false)
	        	break;
		}
		if(i==requestors.size())
			return true;
		else
		    return false;
	}

	@Override
	public int[][] findMatching(DeviceGraph graph) {
		// TODO Auto-generated method stub
		
		GraphConstructor GC = new GraphConstructor();
		SRequestor[] requestors = GC.GetRequesters(graph) ;
		
	    
		int AG[][] = GC.GetAdjacentgraph(graph);
		
		
		int[][] RG= new int[graph.getR().length][graph.getH().length];
		
		
			for(int j = 0; j< graph.getH().length ; j++)
			{
				for(int i = 0; i < graph.getR().length; i++)
				{
					if(AG[i][j] > 0 )
					{
						if(AG[i][j] >= requestors[i].unitsOfWork && (!(requestors[i].done)))
						{
							RG[i][j] = requestors[i].unitsOfWork;
							requestors[i].done = true;
							for(int k =0; k<graph.getR().length;k++)
							{
								AG[k][j] = AG[k][j]-requestors[i].unitsOfWork;
							}
						}
						else
						{
							int t =i;
							int tmp = AG[i][j];
							while((tmp < requestors[i].unitsOfWork) && (t>=0))
							{
								RG[t][j]=0;
								tmp = tmp + RG[t][j];
								t--;
							}
							for(int p=t;p<=i;p++)
							{
								RG[p][j]=0;
							}
							requestors[i].done = true;
							AG[i][j] = AG[i][j]-requestors[i].unitsOfWork;											
						}			
					} 
				}
			}
			
			int[][] matching = new int[graph.getR().length][graph.getH().length];
			
			
			for(int j = 0; j< graph.getH().length ; j++)
			{
				for(int i = 0; i < graph.getR().length; i++)
				{
					if(RG[i][j] > 0)
					{
						matching[i][j] = 1;
					}
				}
			}	
			
			for(int j = 0; j< graph.getR().length ; j++)
			{
				for(int i = 0; i < graph.getH().length; i++)
				{
					if(matching[i][j] == 1)
					{
						matching[i][0] = j;
					}
				}
			}	
			
			int[][] matching2 = new int[graph.getR().length][1];
			
			for(int i = 0; i< graph.getR().length ; i++)
			{
					matching2[i][0] = matching[i][0];

			}	
			
		return matching2;
	}
}
